package strings

import (
	"errors"
	"fmt"
	"github.com/fishtailstudio/imgo"
	"github.com/rwcarlsen/goexif/exif"
	"os"
	"path/filepath"
	"strings"
	"sync"
)

var wg sync.WaitGroup
var runDir string

func Test() {

	runDir, _ = filepath.Abs(filepath.Dir(os.Args[0]))

	s, err := tree(runDir)

	if err != nil {
		fmt.Println(err)
		return
	}

	if len(s) == 0 {
		fmt.Println("找不到要处理的jpg图片")
		return
	}

	err = os.MkdirAll(runDir+"/outs", os.ModePerm)

	if err != nil {
		fmt.Println(err)
		return
	}

	// 0-9 一个协程处理 10-19 二个协程处理...
	// 根据图片数自动生成协程数
	routineCount := len(s)/10 + 1
	var last int

	for i := 0; i < routineCount; i++ {
		wg.Add(1)

		if i == routineCount-1 {
			last = len(s)%10 + i*10
		} else {
			last = (i + 1) * 10
		}
		go resizeImg(s[i*10 : last])
	}

	wg.Wait()
}

func resizeImg(s []string) {
	defer wg.Done()

	for _, path := range s {
		s := strings.Split(path, "/")
		fileName := s[len(s)-1]

		orientation, err := getImageOrientation(path)
		if err != nil {
			fmt.Println(err)
		}
		if orientation == "8" {
			imgo.Load(path).Resize(1200, 0).Rotate(-90).Save(runDir + "/outs/" + fileName)
		} else {
			imgo.Load(path).Resize(1200, 0).Save(runDir + "/outs/" + fileName)
		}

		fmt.Printf("图片%s压缩处理完毕\n", path)
	}

}

func tree(path string) ([]string, error) {

	dirs, err := os.ReadDir(path)

	if err != nil {
		fmt.Println(err)
		return []string{}, err
	}

	var s []string

	for _, file := range dirs {

		currentPath := strings.TrimRight(path, "/") + "/"

		if strings.HasSuffix(strings.ToLower(file.Name()), ".jpg") {
			s = append(s, currentPath+strings.ToLower(file.Name()))
		} else if file.IsDir() {
			files, _ := tree(currentPath + file.Name())
			s = append(s, files...)
		}

	}

	return s, nil
}

func getImageOrientation(filename string) (string, error) {
	f, err := os.Open(filename)
	if err != nil {
		return "0", err
	}
	defer f.Close()

	x, err := exif.Decode(f)
	if err != nil {
		return "0", err
	}

	// 根据EXIF方向标识调整宽度和高度
	orientation, err := x.Get(exif.Orientation)
	if err == nil {
		return orientation.String(), nil
	}

	return "0", errors.New("出错了")
}
